#include "Gamestate.h"

#include "map.h"
#include "player.h"
#include "StaticObject.h"
#include "Unit.h"



namespace Putin{

typedef std::map<int,Unit*>			UnitMap;
typedef std::map<int,StaticObject*> ObjectMap;

Gamestate::Gamestate(Map* map, int numPlayers)
{
	mMap = map;
	mPlayers.reserve(numPlayers);
	mNumPlayers = numPlayers;
	mNextId = 1;
}

Gamestate::~Gamestate()
{
	// Clear stuff
	for each( Player* p in mPlayers)
	{
		delete p;
	}

	for each( std::pair<int,Unit*>  up in mUnits)
	{
		delete up.second;
	}
}

bool Gamestate::add(Unit* unit)
{
	if( mUnits.find(unit->getID()) == mUnits.end() )
	{
		mUnits[unit->getID()] = unit;
		return true;
	}
	else
	{
		return false; // ID duplicate. Should not exist..
	}
}
	
bool Gamestate::add(StaticObject* obj)
{
	if( mObjects.find(obj->getID()) == mObjects.end() )
	{
		mObjects[obj->getID()] = obj;
		return true;
	}
	else
	{
		return false; // ID duplicate. Should not exist..
	}
}

void Gamestate::add(Player* p)
{
	mPlayers.push_back(p);
}

Unit* Gamestate::getUnit(int id)
{
	if( mUnits.find(id) != mUnits.end())
	{
		return mUnits[id];
	}
	else
	{
		return NULL;
	}
}

StaticObject* Gamestate::getObject(int id)
{
	if( mObjects.find(id) != mObjects.end())
	{
		return mObjects[id];
	}
	else
	{
		return NULL;
	}
}

void Gamestate::removeUnit(int id)
{
	if( getUnit(id) )
	{
		// This should call the destructor and free memory
		// TODO: Verify that this is the case in MSVC 2008
		mUnits.erase(id);
	}

}

void Gamestate::removeObject(int id)
{
	if( getObject(id) )
	{
		// This should call the destructor and free memory
		// TODO: Verify that this is the case in MSVC 2008
		mObjects.erase(id);
	}
}

Map* Gamestate::getMap()
{
	return mMap;
}

int Gamestate::nextId()
{
	return mNextId++;
}


void Gamestate::select(int id)
{
	this->mSelected[id] = true;
}

void Gamestate::deselect(int id)
{
	this->mSelected.erase(id);
}

void Gamestate::clearSelection()
{
	this->mSelected.clear();
}

}

